package eaa.tgi.scrum.repositories;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import eaa.tgi.scrum.domain.StoredFile;

@Repository
public class FileRepository {

	protected EntityManager entityManager;
	
	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	public List<StoredFile> findFilesOfProject(Long projectId) {
		
		try {
			
			List<StoredFile> files = (List<StoredFile>) entityManager.createQuery("SELECT f FROM StoredFile f WHERE f.projectId = :projectId")
												                           .setParameter("projectId", projectId).getResultList();	
		
			return files;
			
		} catch (NoResultException userNotFoundException) {
			return null;
		}
	}
	
	@Transactional
	public void persist(StoredFile file) {
		entityManager.persist(file);	
	}

}
